package com.runjian.rundo.iot.agent.iec104.parser.frame.control.process;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.runjian.rundo.iot.agent.iec104.consts.Ti;
import com.runjian.rundo.iot.agent.iec104.parser.frame.*;

import cn.hutool.core.util.ByteUtil;
import com.runjian.rundo.iot.agent.iec104.parser.frame.control.base.TaControl;
import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;


/**
 * C_SE_NA_1(48, "遥调设点,归一化(参数设置)")
 *
 * @author CaoQingHua
 */
@Getter
@Setter
public class C_SE_NA_1 extends TaControl {

    @Override
    public void analysisInfo(byte[] msg) {
        if (this.getSq()) {
            //地址连续
            int sAddress = ByteUtil.bytesToInt(new byte[]{msg[12], msg[13], msg[14], 0x00});
            for (int i = 0; i < this.getNumber(); i++) {
                this.addInfoElement(InfoElement.<Short>builder()
                        .address(sAddress + i)
                        .value(ByteUtil.bytesToShort(new byte[]{msg[15 + i * 3], msg[16 + i * 3]}))
                        .qds((short) (msg[17 + i * 3] & 0xff))
                        .build());
            }
        } else {
            for (int i = 0; i < this.getNumber(); i++) {
                this.addInfoElement(InfoElement.<Short>builder()
                        .address(ByteUtil.bytesToInt(new byte[]{msg[12 + (6 * i)], msg[13 + (6 * i)], msg[14 + (6 * i)], 0x00}))
                        .value(ByteUtil.bytesToShort(new byte[]{msg[15 + i * 6], msg[16 + i * 6]}))
                        .qds((short) (msg[17 + i * 6] & 0xff))
                        .build());
            }
        }
    }

    /**
     * 初始化处理
     */
    @Override
    public void init() {
        super.init();
        // 类型
        this.setTi(Ti.C_SE_NA_1);
    }

    @Override
    public void addControlInfoElement(int address, Object value) {
        if (!StrUtil.isNumeric(value.toString())) {
            Assert.isTrue(Boolean.FALSE, "值必须是短整型数字");
        }
       super.addControlInfoElement(address,value);
    }

    /**
     * 写入byteBuf
     * @param assembleByteBuf 字对缓存对象
     * @param infoElement 信息对象
     */
    public void writeInfoContent(ByteBuf assembleByteBuf, InfoElement<Object> infoElement) {
        assembleByteBuf.writeBytes(ByteUtil.shortToBytes((Short) infoElement.getValue()));
    }

}
